import os
import csv
import easyocr

def scan(ocr_result):
    dict = {'姓名':'', '采样时间':'', '检测结果':''}
    for item in ocr_result:
        y = item[0][0][1]
        if item[1] == '姓名':
            result2 = [(abs(x[0][0][1]-y), x[1]) for x in ocr_result if x[1] != '姓名']
            print(result2)
            result2.sort(key=lambda x: x[0])
            dict['姓名'] = result2[0][1]
        if item[1] == '采样时间':
            result2 = [(abs(x[0][0][1]-y), x[1]) for x in ocr_result if x[1] != '采样时间']
            result2.sort(key=lambda x: x[0])
            dict['采样时间'] = result2[0][1]
        if item[1] == '检测结果':
            result2 = [(abs(x[0][0][1]-y), x[1]) for x in ocr_result if x[1] != '检测结果']
            result2.sort(key=lambda x: x[0])
            dict['检测结果'] = result2[0][1]
    return dict

BASE_PICTURE_DIR = "pictures"

def main():
    fieldnames = ['文件名', '姓名', '采样时间', '检测结果']
    row_list = []

    reader = easyocr.Reader(['ch_sim','en']) 
    for filename in os.listdir(BASE_PICTURE_DIR):
        result = reader.readtext(os.path.join(BASE_PICTURE_DIR, filename))
        print(filename)
        print(result)
        # dict = {'姓名':'test', '采样时间':'test', '检测结果':'test'}
        dict = scan(result)
        dict['文件名'] = filename
        row_list.append(dict)
    with open('results.csv', 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for row_dict in row_list:
            writer.writerow(row_dict)

if __name__ == "__main__":
    main()